<template>
  <div class="all">
    <div class="top">
      <el-row>
        <el-form ref="form" inline label-position="left">
          <el-col :span="3">
            <el-form-item label="设备：">
              <Selects v-model="query.equipment_id" action="equipmentList" :query="{ add_field: 'coding' }" refresh />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="设备台账：">
              <el-input v-model="query.equipment_list" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="计划编号：">
              <el-input v-model="query.coding" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="车间：">
              <Selects v-model="query.workshop_id" action="factoryList" :query="{ category: 2 }" refresh />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="生产线：">
              <Selects v-model="query.line_id" action="factoryList" :query="{ category: 3 }" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="工 位：">
              <Selects v-model="query.process_id" action="factoryList" :query="{ category: 4 }" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="是否停机：">
              <SelfSelect v-model="query.halt" :show-list="halt" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="周 期：">
              <el-input v-model="query.period" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="周期单位：">
              <SelfSelect v-model="query.period_unit" :show-list="planUnit" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="负责人：">
              <Selects v-model="query.admin_id" action="adminList" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="状 态：">
              <SelfSelect v-model="query.status" :show-list="switchOption2" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="专业：">
              <SelfSelect v-model="query.profession" :show-list="planSpecial" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-button style="margin-top: 38%" icon="el-icon-search" type="primary" @click="index">查找</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-row class="btns">
        <el-button v-if="roles.includes('ProjectPlan5Add')" type="primary" icon="el-icon-circle-plus-outline" @click="handleAdd">增加</el-button>
        <el-button type="primary" icon="el-icon-printer" @click="exportDialog">导出</el-button>
        <div v-if="roles.includes('ProjectPlan5Import')" class="buttonBox">
          <el-upload :show-file-list="false" action="" :before-upload="file => workbook(file)">
            <el-button type="primary" icon="el-icon-edit" size="mini">批量导入</el-button>
          </el-upload>
        </div>
        <el-button v-if="roles.includes('ProjectPlan5Delete')" type="danger" icon="el-icon-delete" @click="delBtn">删除</el-button>
        <el-button v-if="roles.includes('ProjectPlan5Import')" type="primary" icon="el-icon-download" @click="downloadExcel">下载模板</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="refresh">刷新</el-button>
      </el-row>
      <span class="total">总数：{{ total }}</span>
    </div>
    <div class="main">
      <div class="table">
        <el-table ref="multipleTable" v-loading="loading" border tooltip-effect="dark" stripe width="100%" :data="dataList" @selection-change="handleSelectionChange">
          <el-table-column label="序号" type="index" align="center" width="50" />
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column prop="coding" label="编号" align="center" width="200" />
          <el-table-column prop="equipment" label="设备-编号" align="center" width="240" />
          <el-table-column prop="workshop" label="车间" align="center" width="160" />
          <el-table-column prop="line" label="生产线" align="center" width="160" />
          <el-table-column prop="process" label="工位" align="center" />
          <el-table-column prop="task_param_list" label="任务列表" align="left" width="500" />
          <el-table-column prop="member_list" label="执行人" align="center" width="120" />
          <el-table-column prop="period" label="周期" align="center" />
          <el-table-column prop="period_unit" label="周期单位" align="center" />
          <el-table-column prop="halt" label="是否停机" align="center" />
          <el-table-column prop="admin" label="负责人" align="center" />
          <el-table-column prop="expect_man_minutes" label="期望工时（分钟）" align="center" width="120" />
          <el-table-column prop="execute_time" label="执行时间" align="center" width="140" />
          <el-table-column prop="task_long" label="任务时长" align="center" />
          <el-table-column prop="next_time" label="下个日期" align="center" width="140" />
          <el-table-column prop="name" label="状态" align="center">
            <template scope="{row}">
              <div v-html="row.status_table" />
            </template>
          </el-table-column>
          <el-table-column prop="category" label="计划类别" align="center" />
          <el-table-column prop="profession" label="专业" align="center" />
          <el-table-column prop="sort" label="排序" align="center" />
          <el-table-column v-if="roles.includes('ProjectPlan5Detail' || 'ProjectPlan5Delete')" label="操作" fixed="right" width="180" align="center">
            <template scope="{row}">
              <el-button v-if="roles.includes('ProjectPlan5Detail')" type="primary" @click="goDetail(row.id)">编辑</el-button>
              <el-button v-if="roles.includes('ProjectPlan5Delete')" type="danger" @click="handleDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="page" background :page-size="query.limit" align="center" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
      </div>
    </div>
    <el-dialog title="请选择导出字段" :visible.sync="excelDialog" width="60%">
      <div>
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;" />
        <el-checkbox-group v-model="needExport" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="title in tableHead" :key="title" class="checkStyle" :label="title" />
        </el-checkbox-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="excelDialog = false">取 消</el-button>
        <el-button type="primary" @click="exportExcel">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import API from '@/api/project/plan'
import { halt, planUnit, switchOption2, planSpecial, need } from '@/utils/option'
import Selects from '@/components/select-search'
import { planTables } from '@/utils/Table'
import SelfSelect from '@/components/select-o'
import XLSX from 'xlsx'
import { mapGetters } from 'vuex'
const tableOptions = ['计划编号', '设备编号', '设备名称', '车间', '生产线', '工位', '存放位置', '任务', '执行人', '负责人', '执行时间', '周期', '周期单位', '期望工时（分钟）', '任务时长', '是否停机', '下个日期', '状态', '计划类别', '专业', '排序']
export default {
  components: {
    SelfSelect,
    Selects
  },
  inject: ['goUrl', 'costStatus', 'reload'],
  data() {
    return {
      dataList: [],
      total: 0,
      loading: true,
      query: {
        limit: 15,
        page: 1,
        category_id: 5
      },
      halt,
      planUnit,
      switchOption2,
      planSpecial,
      need,
      exportList: [],
      excelDialog: false,
      needExport: ['计划编号', '设备编号', '设备名称', '车间', '生产线', '工位', '存放位置', '任务', '执行人', '负责人', '执行时间', '周期', '周期单位', '期望工时（分钟）', '任务时长', '是否停机', '下个日期', '状态', '计划类别', '专业', '排序'],
      isIndeterminate: true,
      tableHead: tableOptions,
      checkAll: true,
      planTables,
      multipleSelection: []
    }
  },
  created() {
    const query = JSON.parse(sessionStorage.getItem('plan5'))
    if (query) {
      this.query = query
      sessionStorage.removeItem('plan5')
    }
    this.index()
    window.addEventListener('keydown', this.handKeyCode, true)
  },
  computed: {
    ...mapGetters(['roles']),
    pages() {
      return this.total / 1000 + 1
    }
  },
  methods: {
    index() {
      this.loading = true
      API.planList(this.query).then(res => {
        this.dataList = res.data.data.data
        this.total = res.data.data.total
      }).finally(() => {
        this.loading = false
      })
    },
    handKeyCode(e) {
      if (e.keyCode === 13 || e.keyCode === 32) {
        this.index()
      }
    },
    setStorage() {
      sessionStorage.setItem('plan5', JSON.stringify(this.query))
    },
    handleAdd() {
      this.setStorage()
      this.goUrl('/project/plan5/add')
    },
    goDetail(id) {
      const url = `/project/plan5/edit/${id}`
      this.setStorage()
      this.goUrl(url)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    refresh() {
      this.reload()
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API.delete(id).then(res => {
          if (res.data.error_code !== 1) {
            this.$message.error(res.data.message)
          } else {
            this.$message.success('删除成功')
            this.setStorage()
            this.index()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    downloadExcel() {
      const a = document.createElement('a')
      a.href = 'https://d.ubeiyun.com/xls/专业点检.xlsx'
      a.download = '专业点检.xlsx'
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    workbook(file) {
      this.loading = true
      const reader = new FileReader()
      const self = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = XLSX.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        const postData = {}
        postData.outData = outData
        postData.planCategory = 5
        API.excel(postData).then(response => {
          if (response.data.error_code === 1) {
            self.$message.success(`恭喜你，操作成功`)
            self.loading = false
            self.index()
          } else {
            self.loading = false
            self.$message.error(response.data.message)
            self.index()
          }
        }).finally(() => {
          self.loading = false
        })
      }
      reader.readAsBinaryString(file)
      return false
    },
    exportDialog() {
      this.excelDialog = true
    },
    handleCheckAllChange(val) {
      this.needExport = val ? tableOptions : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.tableHead.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableHead.length
    },
    toExcel() {
      const exportData = []
      const exportTitle = []
      const titleObj = this.planTables
      exportData.push(this.needExport)
      for (const keys of this.needExport) {
        exportTitle.push(Object.keys(titleObj).find(key => titleObj[key] === keys))
      }
      this.exportList.forEach(item => {
        const arr = []
        for (const key of exportTitle) {
          arr.push(item[key])
        }
        exportData.push(arr)
      })
      const ws = XLSX.utils.aoa_to_sheet(exportData)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      /* save to file */
      XLSX.writeFile(wb, '维护-专业点检.xlsx')
      this.excelDialog = false
      this.loading = false
    },
    async getExcel(condition) {
      this.exportList = []
      const res = await API.planList(condition)
      const exportList = res.data.data.data
      const total = res.data.data.total
      this.exportList.push(...exportList)
      if (this.exportList.length === total) {
        this.isLoading = false
        this.toExcel()
      }
    },
    allExcel() {
      this.isLoading = true
      const arr = Object.keys(this.query)
      const len = arr.length
      if (len > 8 || this.query.admin_id || this.query.equipment_id || this.query.line_id || this.query.process_id || this.query.workshop_id) {
        console.log('带条件的导出')
        const condition = this.query
        condition.limit = this.total
        condition.page = 1
        this.getExcel(condition)
      } else {
        for (let i = 1; i <= this.pages; i++) {
          const condition = {
            limit: 1000,
            page: i,
            category_id: 5
          }
          this.getExcel(condition)
        }
      }
    },
    exportExcel() {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        this.exportList = this.multipleSelection
        this.toExcel()
      } else {
        this.allExcel()
      }
    },
    delBtn() {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        const idArray = []
        this.multipleSelection.forEach(item => {
          idArray.push(item.id)
        })
        const id = idArray.join(',')
        this.handleDel(id)
      } else {
        this.$message('请先选择，然后再删除')
      }
    }
  }
}
</script>
